package com.ilikesoup.instant.compare;

import java.util.Objects;
import java.util.function.BiPredicate;

/**
 * 比较器，区别于 {@link java.util.Comparator}，它是用来比较两个对象关键字段差异的
 *
 * @param <L>
 * @param <R>
 */
public class Comparer<L, R> {
    private final L left;
    private final R right;
    private final BiPredicate commonComparer;
    private final CompareResult<L, R> compareResult;

    public Comparer(L left, R right) {
        this(left, right, Objects::equals);
    }

    public Comparer(L left, R right, BiPredicate commonComparer) {
        this.left = Objects.requireNonNull(left);
        this.right = Objects.requireNonNull(right);
        this.commonComparer = Objects.requireNonNull(commonComparer);
        this.compareResult = new CompareResult<>(left, right);
    }

    public <V> void process(ComparePair<L, R, V> comparePair) {
        BiPredicate<V, V> predicate;
        if((predicate = comparePair.getComparer()) == null) {
            predicate = commonComparer;
        }
        V leftVal = comparePair.getLeft().apply(left);
        V rightVal = comparePair.getRight().apply(right);
        compareResult.addItem(leftVal, rightVal, comparePair.copyOf(predicate), !predicate.test(leftVal, rightVal));
    }

    public CompareResult<L, R> getResult() {
        return compareResult;
    }

}
